package com.archeanx.libx.http;


import android.util.Log;


import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * http工具
 */
public class XHttpUtil {

    /**
     *  生成 Retrofit.Builder
     * @param okHttpClient httpClient
     * @param baseUrl 请求域名
     * @return Retrofit.Builder
     */
    public static Retrofit.Builder getRetrofitBuilder(OkHttpClient okHttpClient, String baseUrl) {
        return new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
    }

    /**
     * 生成一个okhttp的builder，开发者可以继续使用
     */
    public static OkHttpClient.Builder getOkhttpBuilder() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .cookieJar(new XCookieJarImpl())
                //https配置
                .sslSocketFactory(XHttpUtil.getSSLSocketFactory(), XHttpUtil.trustManager)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .connectTimeout(3, TimeUnit.SECONDS)
                //强制增加一个标识android
                .addInterceptor(new XUserAgentInterceptor("Android" + XUserAgentInterceptor.getUserAgent()));
        if (XHttpHelper.getInstance().isShowBodyLogging()) {
            builder.addNetworkInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.d("---Http-body--", message);
                }
            }).setLevel(HttpLoggingInterceptor.Level.BODY));
        }
        if (XHttpHelper.getInstance().isShowHeadLogging()) {
            builder.addNetworkInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.d("---Http-head--", message);
                }
            }).setLevel(HttpLoggingInterceptor.Level.HEADERS));
        }
        return builder;
    }


    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            final SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[]{trustManager}, new SecureRandom());
            return context.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static final X509TrustManager trustManager = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    };

    /**
     * 计算页数
     *
     * @param totalRows 总行数
     * @param pageLimit 每页行数
     * @return 总页数
     */
    public static int pageNumber(int totalRows, int pageLimit) {
        return totalRows % pageLimit > 0 ? (totalRows / pageLimit) + 1 : totalRows / pageLimit;
    }
}
